package ActiveMQ.pb;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by brossdong on 2017/12/16.
 */
public class Publish {

    //连接工厂
    private ConnectionFactory connectionFactory;

    //连接对象
    private Connection connection;

    //session对象
    private Session session;

    //生产者
    private MessageProducer messageProducer;


    public Publish() {
        try {
            this.connectionFactory = new ActiveMQConnectionFactory(
                    ActiveMQConnectionFactory.DEFAULT_USER,
                    ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                    "tcp://localhost:61616");
            connection = this.connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(null);
        }catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage() throws Exception {
        Destination destination = session.createTopic("topic1");
        TextMessage msg = session.createTextMessage("我是内容");
        messageProducer.send(destination,msg);
    }

    public static void main(String[] args) {
        Publish p = new Publish();
        try {
            p.sendMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
